//
//  ViewController.swift
//  MyZhiHuDaily
//
//  Created by joke on 16/1/12.
//  Copyright © 2016年 joke. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import AlamofireImage
class ViewController: UIViewController,UIScrollViewDelegate,UITableViewDelegate{

    @IBOutlet var TopPageControl: UIPageControl!
    @IBOutlet var StoryTableView: UITableView!
    @IBOutlet var TopScrollView: UIScrollView!
    
    
    var topData = [TopViewData]()
    var timer:NSTimer!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.StoryTableView.numberOfRowsInSection(1)
        self.TopPageControl.numberOfPages = 3
        self.TopPageControl.currentPage = 1
        self.TopPageControl.currentPageIndicatorTintColor = UIColor.redColor()
        self.TopPageControl.pageIndicatorTintColor = UIColor.whiteColor()
//        getTopData()
//        for (index,data) in self.topData.enumerate() {
//            var imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
//            imageView.image = data.image
//            self.TopScrollView.addSubview(imageView)
//        }
        for i in 1...3 {
            let image = UIImage(named: "\(i).jpg")
            let x = CGFloat(i-1) * self.view.frame.width
            var imageView = UIImageView(frame: CGRect(x: x, y: 0, width: self.view.frame.width, height: self.view.frame.height))
            imageView.image = image
            self.TopScrollView.pagingEnabled = true
            self.TopScrollView.showsHorizontalScrollIndicator = true
            self.TopScrollView.scrollEnabled = true
            self.TopScrollView.addSubview(imageView)
            self.TopScrollView.delegate = self
        }
        self.TopScrollView.contentSize = CGSizeMake((self.view.frame.width*6),self.TopScrollView.frame.height)
        addTimer()
        
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        let width = self.view.frame.width
        let offsetX = scrollView.contentOffset.x
        let index = (offsetX + width/2) / width
        self.TopPageControl.currentPage = Int(index)
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        removeTimer()
    }
    
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        addTimer()
    }
    
    func addTimer() {
        timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "nextImage", userInfo: nil, repeats: true)
    }
    
    func removeTimer() {
        timer.invalidate()
    }
    
    
    func nextImage() {
        var pageIndex = self.TopPageControl.currentPage
        if pageIndex == 3 {
            pageIndex = 0
        } else {
            pageIndex += 1
        }
        var offsetX = CGFloat(pageIndex) * self.view.frame.width
        self.TopScrollView.setContentOffset(CGPointMake(offsetX, 0), animated: true)
    }
    
    func getTopData() {
        var myData = TopViewData()
        Alamofire.request(.GET, "http://news-at.zhihu.com/api/4/news/latest").responseJSON { (data) -> Void in
            let result = data.result
            switch result{
            case .Success(_):
                if let value = data.result.value {
                    let json = JSON(value)
                    for index in 0...4 {
                        myData.imageUrl = json["top_stories"][index]["image"].stringValue
                        myData.ga_prefix = json["top_stories"][index]["ga_prefix"].stringValue
                        myData.id = json["top_stories"][index]["id"].intValue
                        myData.title = json["top_stories"][index]["title"].stringValue
                        myData.type = json["top_stories"][index]["type"].intValue
                        self.topData.append(myData)
                    }
                    for (index,data) in self.topData.enumerate() {
                        print(data.imageUrl)
                        Alamofire.request(.GET, data.imageUrl).responseImage(completionHandler: { (data) -> Void in
                            switch data.result {
                            case .Success(_):
                                if let image:UIImage = data.result.value {
                                    //print(data.result.value)
                                    self.topData[index].image = image
                                    //print(self.topData[index].image)
                                }
                            case .Failure(let error):
                                print("there is an error\(error.userInfo)")
                            }
                        })
                    
                    }
                
                }
            case .Failure(let error):
                print("there is an error,\(error)")
            }
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

